# -*- coding: utf-8 -*-
# @File:     chat.py
# @Author:
# @DateTime: 2025/10/24/11:01
from app.api.chat.scheme.chat import *
from app.models.chat import Dialog, DialogHistory, RAGUploadFile
from app.utils.curd_base import ModelCRUD
from langchain_core.messages import HumanMessage, ToolMessage, AIMessage

from app.utils.file_storage import get_storage_file


class CRUDChatDialog(ModelCRUD):

    model = Dialog


class CRUDChatDialogHistory(ModelCRUD):

    model = DialogHistory


class CRUDRAGUploadFile(ModelCRUD):

    model = RAGUploadFile

    @staticmethod
    def serializer(queryset, only: tuple = (), date_format: str = None, datetime_format: str = None,
                   time_format: str = None):
        li = list()
        for instance in queryset:
            data = instance.to_dict(only=only, date_format=date_format, datetime_format=datetime_format, time_format=time_format)
            data['path_url'] = get_storage_file(data.get('path')) if data.get('path') else None
            li.append(data)
        return li


def create_dialog(data, db):
    """
    创建对话
    """

    crud = CRUDChatDialog()
    able_filter = [
        {'name': 'dialog_uid', 'source_filed': 'dialog_uid', 'lookup_expr': 'eq', 'label': '等于dialog_uid', 'type': str, 'method': None, 'required': True},
    ]
    instance = crud.filter(crud.queryset(db), data, able_filter_list=able_filter).first()
    if not instance:
        instance = crud.create(db, data=CreateDialog.validate(data))
    return instance


def create_dialog_history(data, db):
    """
        创建对话内容
        """
    # print(data)
    crud = CRUDChatDialogHistory()
    instance = crud.create(db, data=CreateDialogHistory.validate(data))
    return instance


def create_history_message(dialog_uid, db, history: list):
    crud = CRUDChatDialog()
    able_filter = [
        {'name': 'dialog_uid', 'source_filed': 'dialog_uid', 'lookup_expr': 'eq', 'label': '等于dialog_uid', 'type': str, 'method': None, 'required': True},
    ]
    instance = crud.filter(crud.queryset(db), {'dialog_uid': dialog_uid}, able_filter_list=able_filter).first()
    if instance:

        crud_history = CRUDChatDialogHistory()

        able_filter_history = [
            {'name': 'dialog_id', 'source_filed': 'dialog_id', 'lookup_expr': 'eq', 'label': '等于dialog_id', 'type': int, 'method': None, 'required': True},
        ]
        queryset = crud_history.filter(crud_history.queryset(db), {'dialog_id': instance.id}, able_filter_list=able_filter_history)
        queryset = crud_history.order_by(queryset, ('id', ))
        # print(queryset)
        for ins in queryset:
            if ins.role == 'user':
                history.append(HumanMessage(content=ins.content))
            else:
                history.append(AIMessage(content=ins.content))


process_filter_list = [
    {'name': 'user_id', 'source_filed': 'user_id', 'lookup_expr': 'eq', 'label': 'userID', 'type': str, 'method': None, 'required': True},
    {'name': 'id', 'source_filed': 'id', 'lookup_expr': 'in', 'label': 'ID', 'type': list, 'method': None, 'required': True},

]


def select_file_collection_name(file_id_list, db, user_id):
    crud = CRUDRAGUploadFile()

    filter_data = {
        'user_id': user_id,
        'id': file_id_list,
    }
    queryset = crud.get_all_queryset(db, req_data=filter_data, able_filter_list=process_filter_list)

    li = []
    for instance in queryset:
        li.append(instance.vector_uid)
    return li

